package com.yeyks.commonReference.service.vip.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.yeyks.common.dto.mq.MiniCardOrderSuccessMessage;
import com.yeyks.common.em.pay.PayTypeEnum;
import com.yeyks.common.em.vip.MemberCardEnableOrderStatusEnum;
import com.yeyks.common.em.vip.MemberCardEnableRecordStatusEnum;
import com.yeyks.common.exception.ServiceException;
import com.yeyks.common.utils.TryCatchUtil;
import com.yeyks.commonReference.append.pay.PayService;
import com.yeyks.commonReference.append.rocketmq.service.producer.MQProducerService;
import com.yeyks.commonReference.service.consumer.MemberCardService;
import com.yeyks.commonReference.service.vip.MemberCardEnableOrderService;
import com.yeyks.commonReference.service.vip.MemberCardEnableRecordService;
import com.yeyks.commonReference.service.vip.MemberCardGiftInfoService;
import com.yeyks.consumer.dal.domain.MemberCard;
import com.yeyks.order.dal.domain.OrderHead;
import com.yeyks.vip.dal.dao.MemberCardEnableRecordMapper;
import com.yeyks.vip.dal.domain.MemberCardEnableOrder;
import com.yeyks.vip.dal.domain.MemberCardEnableRecord;
import com.yeyks.vip.dal.domain.MemberCardGiftInfo;
import com.yeyks.vip.dal.domain.MemberCardSellRelation;
import com.yeyks.vip.param.MemberCardEnableRecordCreateOrderPayRecordParam;
import com.yeyks.vip.service.MemberCardSellRelationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;
import java.util.Objects;


/**
 * <p>
 * 会员卡购买订单支付记录表 服务实现类
 * </p>
 *
 * @author yun
 * @since 2019-08-07
 */
@Service
@Slf4j
public class MemberCardEnableRecordServiceImpl extends ServiceImpl<MemberCardEnableRecordMapper, MemberCardEnableRecord> implements MemberCardEnableRecordService {

    @Autowired
    private MemberCardEnableRecordService memberCardEnableRecordService;
    @Autowired
    private PayService payService;
    @Autowired
    private MemberCardEnableOrderService memberCardEnableOrderService;
    @Autowired
    private MemberCardService memberCardService;
    @Autowired
    private MemberCardGiftInfoService memberCardGiftInfoService;
    @Autowired
    private MemberCardSellRelationService memberCardSellRelationService;
    @Autowired
    private MQProducerService mqProducerService;

    /**
     * v3.4.a
     * 根据订单生成支付信息和支付记录
     */
    @Override
    public Map<String, Object> createOrderPayRecord(MemberCardEnableRecordCreateOrderPayRecordParam param) {
        String payTypeDesc = PayTypeEnum.getDesc(param.getPayTypeInt());
        MemberCardEnableOrder memberCardEnableOrder = memberCardEnableOrderService.getOne(
                new QueryWrapper<MemberCardEnableOrder>()
                        .eq(MemberCardEnableOrder.ORDER_NO, param.getOrderNo())
                        .last("limit 1")
        );
        if (null == memberCardEnableOrder || !memberCardEnableOrder.getStatus().equals(MemberCardEnableOrderStatusEnum.pay_pre.value())) {
            throw new ServiceException("订单不存在或者订单已付款");
        }
        //生成支付信息
        Map<String, Object> map = payService.memberCardEnableorderPay(payTypeDesc, param.getOrderNo(), param.getWxOpenId(), param.getIp());
        //存储支付记录
        try {
            MemberCardEnableRecord memberCardEnableRecord = getOne(
                    new QueryWrapper<MemberCardEnableRecord>()
                            .eq(MemberCardEnableRecord.ORDER_NO, param.getOrderNo())
                            .eq(MemberCardEnableRecord.PAY_TYPE, param.getPayTypeInt())
                            .last("limit 1")
            );
            if (null == memberCardEnableRecord) {
                Date date = new Date();
                memberCardEnableRecord = new MemberCardEnableRecord();
                memberCardEnableRecord.setOrderNo(param.getOrderNo());
                memberCardEnableRecord.setStatus(MemberCardEnableRecordStatusEnum.pay_pre.value());
                memberCardEnableRecord.setPayType(param.getPayTypeInt());
                memberCardEnableRecord.setStartTime(date);
                memberCardEnableRecord.setPayAmount(memberCardEnableOrder.getPayValue());
                memberCardEnableRecord.setCreateTime(date);
                memberCardEnableRecord.setUpdateTime(date);
                boolean save = save(memberCardEnableRecord);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * v3.4.a
     * 会员卡enable订单支付回调
     */
    @Override
    public void payCallback(String orderNo, PayTypeEnum payTypeEnum, WxPayOrderNotifyResult resultCode, Boolean succeeded) {
        try {
            memberCardEnableRecordService.payCallbackT(orderNo, payTypeEnum, resultCode, succeeded);
        } catch (Exception e) {
            log.error("会员卡enable订单支付回调:抛错:orderNo:{},payTypeEnum:{},resultCode:{},succeeded:{},e:{}"
                    , orderNo, payTypeEnum, resultCode, succeeded, e.getMessage());
        }
    }

    //会员卡enable订单支付回调v3.6
    /**
     *
     * {@link MemberCardOnlineServiceImpl#payCallbackT(java.lang.String, com.yeyks.common.em.pay.PayTypeEnum, com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult, java.lang.Boolean)}
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void payCallbackT(String orderNo, PayTypeEnum payTypeEnum, WxPayOrderNotifyResult resultCode, Boolean succeeded) {
        //修改订单
        MemberCardEnableOrder memberCardEnableOrder = memberCardEnableOrderService.getOne(
                new QueryWrapper<MemberCardEnableOrder>()
                        .eq(MemberCardEnableOrder.ORDER_NO, orderNo)
                        .last("limit 1")
        );
        if (null != memberCardEnableOrder && MemberCardEnableOrderStatusEnum.pay_pre.value().equals(memberCardEnableOrder.getStatus())) {
            //更新订单
            boolean update = memberCardEnableOrderService.update(
                    new UpdateWrapper<MemberCardEnableOrder>()
                            .eq(MemberCardEnableOrder.ID, memberCardEnableOrder.getId())
                            .eq(MemberCardEnableOrder.CARD_TYPE, memberCardEnableOrder.getCardType())
                            .set(MemberCardEnableOrder.OVER_TIME, new Date())
                            .set(MemberCardEnableOrder.STATUS, (
                                            succeeded ?
                                                    MemberCardEnableOrderStatusEnum.pay_success.value()
                                                    : MemberCardEnableOrderStatusEnum.pay_fail.value()
                                    )
                            ).set(MemberCardEnableOrder.PAYMENT_METHOD, payTypeEnum.value())
            );
            if (!update) {
                log.error("会员卡enable订单支付回调:订单更新失败:orderNo:{},payTypeEnum:{},resultCode:{},succeeded:{}"
                        , orderNo, payTypeEnum.desc(), resultCode, succeeded);
            }
            //修改订单支付记录
            MemberCardEnableRecord memberCardEnableRecord = getOne(
                    new QueryWrapper<MemberCardEnableRecord>()
                            .eq(MemberCardEnableRecord.ORDER_NO, orderNo)
                            .eq(MemberCardEnableRecord.PAY_TYPE, payTypeEnum.value())
                            .eq(MemberCardEnableRecord.STATUS, MemberCardEnableRecordStatusEnum.pay_pre.value())
                            .last("limit 1")
            );
            if (null != memberCardEnableRecord) {
                //更新订单记录
                update = update(
                        new UpdateWrapper<MemberCardEnableRecord>()
                                .eq(MemberCardEnableRecord.ID, memberCardEnableRecord.getId())
                                .set(MemberCardEnableRecord.STATUS,
                                        (
                                                succeeded ?
                                                        MemberCardEnableRecordStatusEnum.pay_success.value()
                                                        : MemberCardEnableRecordStatusEnum.pay_fail.value()
                                        )
                                )
                                .set(MemberCardEnableRecord.PAY_RETURN_NO, resultCode.getTransactionId())
                                .set(MemberCardEnableRecord.FINISH_TIME, resultCode.getTimeEnd())
                                .set(MemberCardEnableRecord.PAY_RESULT, JSONUtil.toJsonStr(resultCode))
                );
                if (!update) {
                    log.error("会员卡enable订单支付回调:订单支付记录更新失败:orderNo:{},payTypeEnum:{},resultCode:{},succeeded:{}"
                            , orderNo, payTypeEnum.desc(), resultCode, succeeded);
                }
            } else {
                log.error("会员卡enable订单支付回调:订单支付记录不存在:orderNo:{},payTypeEnum:{},resultCode:{},succeeded:{}"
                        , orderNo, payTypeEnum.desc(), resultCode, succeeded);
            }
            //更新卡enable
            if (succeeded) {
                MemberCard memberCard = memberCardService.getOne(
                        new QueryWrapper<MemberCard>()
                                .eq(MemberCard.CARD_NO, memberCardEnableOrder.getCardNo())
                                .eq(MemberCard.CARD_TYPE, memberCardEnableOrder.getCardType())
                                .last("limit 1")
                );
                if (null != memberCard) {
                    update = memberCardService.update(
                            new UpdateWrapper<MemberCard>()
                                    .eq(MemberCard.ID, memberCard.getId())
                                    .set(MemberCard.ENABLE, 1)
                    );
                    if (!update) {
                        log.error("会员卡enable订单支付回调:卡enable更新失败:orderNo:{},payTypeEnum:{},resultCode:{},succeeded:{}"
                                , orderNo, payTypeEnum.desc(), resultCode, succeeded);
                    }
                } else {
                    log.error("会员卡enable订单支付回调:卡不存在:orderNo:{},payTypeEnum:{},resultCode:{},succeeded:{}"
                            , orderNo, payTypeEnum.desc(), resultCode, succeeded);
                }
            }
            //更新附加关系
            if(succeeded){
                switch (memberCardEnableOrder.getCardType()) {
                    case 1:
                        //更新礼物状态
                        MemberCardGiftInfo memberCardGiftInfo = memberCardGiftInfoService.getOne(
                                new QueryWrapper<MemberCardGiftInfo>()
                                        .eq(MemberCardGiftInfo.ORDER_NO, orderNo)
                                        .last("limit 1")
                        );
                        if (Objects.nonNull(memberCardGiftInfo)) {
                            update = memberCardGiftInfoService.update(
                                    new UpdateWrapper<MemberCardGiftInfo>()
                                            .eq(MemberCardGiftInfo.ID, memberCardGiftInfo.getId())
                                            .set(MemberCardGiftInfo.STATUS, 1)
                            );
                            if (!update) {
                                log.error("会员卡enable订单支付回调:礼物记录更新失败:orderNo:{},payTypeEnum:{},resultCode:{},succeeded:{}"
                                        , orderNo, payTypeEnum.desc(), resultCode, succeeded);
                            }
                        } else {
                            log.error("会员卡enable订单支付回调:礼物记录不存在:orderNo:{},payTypeEnum:{},resultCode:{},succeeded:{}"
                                    , orderNo, payTypeEnum.desc(), resultCode, succeeded);
                        }
                        break;
                    case 2:
                        //更新用户记录关系
                        MemberCardSellRelation memberCardSellRelation = memberCardSellRelationService.getOne(
                                new QueryWrapper<MemberCardSellRelation>()
                                        .eq(MemberCardSellRelation.ORDER_NO, orderNo)
                                        .last("limit 1")
                        );
                        if (Objects.nonNull(memberCardSellRelation)) {
                            update = memberCardSellRelationService.update(
                                    new UpdateWrapper<MemberCardSellRelation>()
                                            .eq(MemberCardSellRelation.ID, memberCardSellRelation.getId())
                                            .set(MemberCardSellRelation.STATUS, 2)
                            );
                            if (!update) {
                                log.error("会员卡enable订单支付回调:jip关系更新失败:orderNo:{},payTypeEnum:{},resultCode:{},succeeded:{}"
                                        , orderNo, payTypeEnum.desc(), resultCode, succeeded);
                            }
                        } else {
                            log.error("会员卡enable订单支付回调:jip关系更新失败:orderNo:{},payTypeEnum:{},resultCode:{},succeeded:{}"
                                    , orderNo, payTypeEnum.desc(), resultCode, succeeded);
                        }
                        break;
                }
            }
            //发送线下会员卡支付成功发佣金的通知
            if(succeeded){
                TryCatchUtil.tryCatch(() -> {
                    mqProducerService.sendMiniCardOrderSuccessMessage(new MiniCardOrderSuccessMessage().setOrderNo(orderNo));
                });
            }
        } else {
            log.error("会员卡enable订单支付回调:订单不存在或状态不正确:orderNo:{},payTypeEnum:{},resultCode:{},succeeded:{}"
                    , orderNo, payTypeEnum.desc(), resultCode, succeeded);
        }
    }

}
